package org.apache.lucene.ocean.util;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import org.apache.lucene.store.IndexOutput;
import org.apache.lucene.store.RAMDirectory;
import org.apache.lucene.store.RAMFile;
import org.apache.lucene.store.RAMInputStream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class RAMDirectorySerializer {
  final static Logger LOG = LoggerFactory.getLogger(RAMDirectorySerializer.class);
  
  public static RAMDirectory deserialize(InputStream inputStream) throws IOException {
    VDataInputStream input = new VDataInputStream(inputStream);
    byte[] buffer = new byte[1024];
    RAMDirectory ramDirectory = new RAMDirectory();
    int numFiles = input.readVInt();
    for (int x=0; x < numFiles; x++) {
      String file = input.readString();
      int length = input.readVInt();
      IndexOutput ramOutput = ramDirectory.createOutput(file);
      long readCount = 0;
      while (readCount < length) {
        int toRead = readCount + buffer.length > length ? (int)(length - readCount) : buffer.length;
        input.read(buffer, 0, toRead);
        ramOutput.writeBytes(buffer, toRead);
        readCount += toRead;
      }
      ramOutput.close();
    }
    return ramDirectory;
  }
  
  public static void serialize(RAMDirectory ramDirectory, OutputStream out) throws IOException {
    //ByteArrayIndexOutput output = new ByteArrayIndexOutput();
    VDataOutputStream output = new VDataOutputStream(out);
    byte[] buffer = new byte[1024];
    String[] files = ramDirectory.list();
    output.writeVInt(files.length);
    for (String file : files) {
      output.writeString(file);
      int length = (int)ramDirectory.fileLength(file);
      output.writeVInt(length);
      //LOG.info("file: "+file+" length: "+length);
      RAMInputStream input = (RAMInputStream)ramDirectory.openInput(file);
      RAMFile ramFile = input.getRAMFile();
      Util.copyRamFile(ramFile, output);
      
      /**
      
      long readCount = 0;
      while (readCount < length) {
        int toRead = readCount + buffer.length > length ? (int)(length - readCount) : buffer.length;
        input.readBytes(buffer, 0, toRead);
        output.write(buffer);
        readCount += toRead;
      }
      **/
      //RAMOutputStream ramOutput = (RAMOutputStream)ramDirectory.createOutput(file);
     // ramOutput.writeTo(output);
    }
  }
}
